package com.sise.cn.task.service.impl;

import com.rabbitmq.client.Channel;
import com.sise.cn.task.enumerate.ServerResponseEnum;
import com.sise.cn.task.exception.TaskException;
import com.sise.cn.task.service.AbstractTaskReceiver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author 龚秀峰
 * @version 1.0
 * @date 2020/6/8 20:56
 */
@Component
@Slf4j
public class MessageConsume extends AbstractTaskReceiver {
    private int a = 0;

    @Override
    public void task(Object obj, Channel channel, Message message) throws IOException {
        try {
            if(a == 2){
                throw  new TaskException(ServerResponseEnum.TASK_ERROR);
            }
            //确认消费消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            a++;
            log.info("当前处理的消息是："+obj);
        } catch (Exception e) {
            //丢弃消息，可以在此要求重发消息或者丢弃消息并且记录
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false,false);
            log.error("系统发生异常，原因是{},被丢弃的消息是："+obj,e.getMessage());
        }
    }
}
